#include "WorldKernel.h"
#include "MessagePort.h"
#include "NetMsg.h"
#include "User.h"
#include "EventMgr.h"
#include "MsgAll.h"

namespace cupid
{
void WorldKernel::onUserSignup(MsgSn* sn)
{
	MsgUsn usn;
	usn.SetBuf(sn->GetBuf(),sn->GetLen());
	int sock;
	string name;
	string password;
	usn >> sock;
	usn >> name;
	usn >> password;
	newUser(sock, name, password);
}

void WorldKernel::onUserSignin(MsgSn* sn)
{
	MsgUsn usn;
	usn.SetBuf(sn->GetBuf(),sn->GetLen());
	int sock;
	string name;
	string password;
	usn >> sock;
	usn >> name;
	usn >> password;
	
	User* user = getUser(name);
	if (user)
	{
		if (user->getPassword() != password)
			return;
		user->setSock(sock);
		m_userName2ID[name] = user->getGuid();
		m_userSock2ID[sock] = user->getGuid();
		user->setSignin(true);
		map<int,User*>::iterator itr =	m_userList.begin();
		while(itr != m_userList.end())
		{
			sendFriends(itr->second);
			itr++;
		}
	}
}

void WorldKernel::onUserTalk(MsgSn* sn)
{
	MsgUsn usn;
	usn.SetBuf(sn->GetBuf(),sn->GetLen());
	int sock;
	string tname;
	string data;
	usn >> sock;
	usn >> tname;
	usn >> data;

	User* user = getUserBy(sock);
	User* tuser = getUser(tname);
	if (user && tuser)
	{
		MsgTalk msg;
		msg.create(user->getName().c_str(), getTime(), data.c_str());
		sendClientMsg(user->getSock(), &msg);
		sendClientMsg(tuser->getSock(), &msg);
	}
}

}